﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LandandSurvey.Controls;

namespace LandandSurvey
{
    public partial class ViewUsers : System.Web.UI.Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if (!IsPostBack)
            {
                if ( !IsPostBack )
                {
                    if ( !HasPermission() )
                    {
                        Response.Redirect( "ErrorPermission.aspx?returnurl=ViewUsers.aspx" );
                    }
                }

                landsdbEntities context = new landsdbEntities();
                var result = from i in context.AppUsers
                             select i;

                foreach ( AppUser user in result )
                {
                    UserListItem control = (UserListItem)LoadControl( "Controls/UserListItem.ascx" );
                    control.setup( user );
                    container.Controls.Add( control );
                }
            }
        }

        public bool HasPermission()
        {
            if ( Session[ "user.loggedin" ] == null )
            {
                return false;
            }
            if ( Session[ "user.loggedin" ].ToString() == "true" )
            {
                landsdbEntities container = new landsdbEntities();
                string username = Session[ "user.name" ].ToString();
                AppUser user = ( from i in container.AppUsers
                                 where i.UserName == username
                                 select i ).ToList().FirstOrDefault();
                if ( user != null )
                {
                    if ( user.IsAdmin )
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    }
}